﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace MsAccount
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            var _Result = await LoginAsync(true);
            if (!_Result.HasValue)
            {
                // TODO: error occurred
            }
            else if (_Result.Value)
            {
                this.DataContext = new
                {
                    Name = User.NameFull,
                    Photo = User.PhotoLocation
                };
            }
            else
            {
                // TODO: login failed
            }
        }

        public async Task<bool?> LoginAsync(bool logout)
        {
            try
            {
                var client = new Microsoft.Live.LiveAuthClient()
                {
                    Theme = Microsoft.Live.ThemeType.Light
                };

                // logout
                var can = client.CanLogout;
                if (logout && can)
                    client.Logout();

                // prompt
                var scope = new string[] { "wl.basic", "wl.emails", "wl.skydrive", "wl.photos", "wl.calendars" };
                LoginResult = await client.LoginAsync(scope);

                // and?
                if (LoginResult.Status != Microsoft.Live.LiveConnectSessionStatus.Connected)
                    return false;

                // get profile
                Client = new Microsoft.Live.LiveConnectClient(LoginResult.Session);
                var result = (await Client.GetAsync("me")).Result;

                // get photo
                dynamic photo = (await Client.GetAsync("me/picture")).Result;
                var path = new Uri(photo.location, UriKind.Absolute);

                // persist
                User = new LiveId(result, path);
                return true;
            }
            catch (Exception)
            {
                System.Diagnostics.Debugger.Break();
                return null;
            }
        }

        public static Microsoft.Live.LiveLoginResult LoginResult { get; private set; }
        public static Microsoft.Live.LiveConnectClient Client { get; private set; }
        public static LiveId User { get; private set; }

    }

    public class LiveId
    {
        // used by Live ID

        public LiveId(IDictionary<string, object> result) : this(result, null) { }
        public LiveId(IDictionary<string, object> result, Uri image)
        {
            Id = result.ContainsKey("id") ? result["id"] as string : string.Empty;
            NameFull = result.ContainsKey("name") ? result["name"] as string : string.Empty;
            NameFirst = result.ContainsKey("first_name") ? result["first_name"] as string : string.Empty;
            NameLast = result.ContainsKey("last_name") ? result["last_name"] as string : string.Empty;
            Gender = result.ContainsKey("gender") ? result["gender"] as string : string.Empty;
            Locale = result.ContainsKey("locale") ? result["locale"] as string : string.Empty;

            Uri _Uri;
            if (Uri.TryCreate(result.ContainsKey("link") ? result["link"] as string : string.Empty, UriKind.Absolute, out _Uri))
                Link = _Uri;

            DateTime _Date;
            if (DateTime.TryParse(result.ContainsKey("updated_time") ? result["updated_time"] as string : string.Empty, out _Date))
                UpdatedTime = _Date;

            var _Emails = result.ContainsKey("emails") ? result["emails"] as IDictionary<string, object> : new Dictionary<string, object>();
            EmailPreferred = _Emails.ContainsKey("preferred") ? _Emails["preferred"] as string : string.Empty;
            EmailAccount = _Emails.ContainsKey("account") ? _Emails["account"] as string : string.Empty;

            if (image != null)
            {
                PhotoLocation = image;
                var _PhotoBitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage(image);
                PhotoBitmap = _PhotoBitmap;
            }
        }

        public string Id { get; set; }
        public string NameFull { get; set; }
        public string NameFirst { get; set; }
        public string NameLast { get; set; }
        public Uri Link { get; set; }
        public string Gender { get; set; }
        public string Locale { get; set; }
        public DateTime UpdatedTime { get; set; }
        public string EmailAccount { get; set; }
        public string EmailPreferred { get; set; }
        public Uri PhotoLocation { get; set; }
        public Windows.UI.Xaml.Media.Imaging.BitmapImage PhotoBitmap { get; set; }
    }
}
